package com.hn.common.utils.ding;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiDepartmentCreateRequest;
import com.dingtalk.api.request.OapiDepartmentDeleteRequest;
import com.dingtalk.api.request.OapiDepartmentListRequest;
import com.dingtalk.api.request.OapiDepartmentUpdateRequest;
import com.dingtalk.api.response.OapiDepartmentCreateResponse;
import com.dingtalk.api.response.OapiDepartmentDeleteResponse;
import com.dingtalk.api.response.OapiDepartmentListResponse;
import com.dingtalk.api.response.OapiDepartmentUpdateResponse;
import com.hn.common.exception.DingException;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 描述:
 *   部门管理
 * @author fei
 * @create 2019-06-28 14:32
 */
@Slf4j
public class DingDeptUtils {

    /**
     * 获取部门列表
     *
     * access_token	String	是	调用接口凭证
     * lang	        String	否	通讯录语言（默认zh_CN，未来会支持en_US）
     * fetch_child	Boolean	否	是否递归部门的全部子部门，ISV微应用固定传递false
     * id	        String	是	父部门id（如果不传，默认部门为根部门，根部门ID为1）
     */
    public static List<OapiDepartmentListResponse.Department> list(String id){
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
        OapiDepartmentListRequest request = new OapiDepartmentListRequest();
        request.setId(id);
        request.setHttpMethod("GET");
        try {
            OapiDepartmentListResponse response = client.execute(request, AccessTokenUtil.getToken());
            if (DingConstant.SUCCESS_CODE.equals(response.getErrcode()) ) {
                log.debug("获取部门列表 success,{}", JSONObject.toJSONString(response.getDepartment()));
                return response.getDepartment();
            }
            throw new DingException("获取部门列表异常 fail:,"+response.getErrmsg());
        } catch (ApiException e) {
            throw new DingException("获取部门列表异常 fail:,"+e.getErrMsg());
        }
    }

    /**
     *  根据部门名称获取部门
     * @param deptName
     */
    public static Long getDeptByName(String deptName){
        List<OapiDepartmentListResponse.Department> list = list(null);
        for (OapiDepartmentListResponse.Department dept : list) {
            if(deptName.equals(dept.getName())){
                return dept.getId();
            }
        }
        return null;
    }

    /**
     *  创建部门
     * @param parentId 父部门id
     * @param deptName 部门名称
     */
    public static long createDept(String parentId,String deptName) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/create");
        OapiDepartmentCreateRequest request = new OapiDepartmentCreateRequest();
        // parentId为1,就是根部门
        request.setParentid(parentId);
        // 是否创建一个关联此部门的企业群，默认为false
        request.setCreateDeptGroup(false);
        request.setOrder("100");
        request.setName(deptName);
        try {
            OapiDepartmentCreateResponse response = client.execute(request, AccessTokenUtil.getToken());
            if (DingConstant.SUCCESS_CODE.equals(response.getErrcode()) ) {
                log.debug("创建部门 success,{}",response.getId());
                return response.getId();
            }
            throw new DingException("创建部门失败 fail:,"+response.getErrmsg());
        } catch (ApiException e) {
            throw new DingException("创建部门失败 fail:,"+e.getErrMsg());
        }
    }

    /**
     *  创建根部门下 的部门
     * @param deptName 部门名称
     */
    public static long createDept(String deptName) {
        return createDept("1",deptName);
    }

    /**
     *  更新部门
     * @param deptId
     * @param deptName
     */
    public static void updateDept(String deptId,String deptName) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/update");
        OapiDepartmentUpdateRequest request = new OapiDepartmentUpdateRequest();
        request.setId(Long.valueOf(deptId));
        request.setName(deptName);
        try {
            OapiDepartmentUpdateResponse response = client.execute(request, AccessTokenUtil.getToken());
            if (DingConstant.SUCCESS_CODE.equals(response.getErrcode()) ) {
                log.debug("更新部门 success,{}",response.getId());
            }
            throw new DingException("更新部门失败 fail:,"+response.getErrmsg());
        } catch (ApiException e) {
            throw new DingException("更新部门失败 fail:,"+e.getErrMsg());
        }
    }

    /**
     *  删除部门
     *  (注：不能删除根部门；当部门里有员工，或者部门的子部门里有员工，也不能删除)
     * @param deptId 部门id
     */
    public static void delDept(String deptId) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/delete");
        OapiDepartmentDeleteRequest request = new OapiDepartmentDeleteRequest();
        request.setId(deptId);
        request.setHttpMethod("GET");
        try {
            OapiDepartmentDeleteResponse response = client.execute(request, AccessTokenUtil.getToken());
            if (DingConstant.SUCCESS_CODE.equals(response.getErrcode()) ) {
                log.debug("删除部门 success,{}",deptId);
            }
            throw new DingException("删除部门失败 fail:,"+response.getErrmsg());
        } catch (ApiException e) {
            throw new DingException("删除部门失败 fail:,"+e.getErrMsg());
        }
    }

}
